package com.es.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;


/**
 * @author lizhenzhong
 * @date 2019/5/6
 */
@Configuration
public class EsConfig {
    private Logger logger  = LoggerFactory.getLogger(this.getClass());
    @Value("${elasticsearch.ip}")
    private String ip;
    @Value("${elasticsearch.port}")
    private int port;
    @Value("${elasticsearch.clusterName}")
    private String clusterName;
    TransportClient transportClient = null;
    @Bean
    public TransportClient getTransportClient() {
        logger.info("ElasticSearch初始化开始。。");
        logger.info("要连接的节点1的ip是" + ip + "，端口是" + port + "，集群名为" + clusterName);
        try {
            Settings settings = Settings.builder()
                    .put("cluster.name",clusterName)
                    .put("client.transport.sniff",true)
                    .build();
            transportClient = new PreBuiltTransportClient(settings);
            InetSocketTransportAddress master = new InetSocketTransportAddress(
                    InetAddress.getByName(ip), port
            );
            transportClient.addTransportAddress(master);
            logger.info("ElasticSearch初始化完成。。");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("ElasticSearch初始化失败：" +  e.getMessage(),e);
        }
        return transportClient;
    }
}
